/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package net.qunzhi.modules.cms.service;

import cn.hutool.core.lang.Pair;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import net.qunzhi.common.utils.Constant;
import net.qunzhi.common.utils.LocalDateUtils;
import net.qunzhi.common.utils.PageUtils;
import net.qunzhi.common.utils.Query;
import net.qunzhi.datasource.annotation.DataSource;
import net.qunzhi.modules.cms.query.DailyRecordListQuery;
import net.qunzhi.modules.cms.query.DateInfoQuery;
import net.qunzhi.modules.cms.query.SqlServerDateQuery;
import net.qunzhi.modules.cms.query.StateDateQuery;
import net.qunzhi.modules.cms.vo.*;
import net.qunzhi.modules.sqlserver.dao.XjFlowDataDao;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 西江数据报表
 */
@Service
@DataSource("slave1")
public class XjFlowDataService {
    @Autowired
    private XjFlowDataDao xjFlowDataDao;

    static final Map<Integer,String> xjFlowNameMap;// 西江对应的字段命名
    static
    {
        xjFlowNameMap = new HashMap<Integer, String>();
        xjFlowNameMap.put(1, "sourceFlow1");
        xjFlowNameMap.put(2, "sourceFlow2");
        xjFlowNameMap.put(17, "outFlow1");
        xjFlowNameMap.put(18, "outFlow2");
    }
    static final Map<Integer,String> xjPressNameMap;// 西江对应的字段命名
    static
    {
        xjPressNameMap = new HashMap<Integer, String>();
        xjPressNameMap.put(17, "outPress1");
        xjPressNameMap.put(18, "outPress2");
    }

    @Transactional
    public void getFlowData(Long id) {

    }

//    public List<DailyRecordVO> getFlowData(List<DailyRecordVO> xjList, DailyRecordListQuery query) {
//        String maxTime = xjFlowDataDao.getMaxTime(query.getStartDateTime().toString().replaceAll("T", " ")
//                , query.getEndDateTime().toString().replaceAll("T", " "));
//        Map<String, BigDecimal> insFlowData = xjFlowDataDao.getInsFlowData(maxTime);// 获取瞬时数据
//        Map<String, BigDecimal> pmFlowData = xjFlowDataDao.getFlowData(query.getDate().toString() + " 14:00"
//                , query.getDate().toString() + " 16:00"); // 获取当日两点至四点累计流量
//        Map<String, BigDecimal> dayFlowData = xjFlowDataDao.getFlowData(query.getStartDateTime().toString().replaceAll("T", " ")
//                , query.getEndDateTime().toString().replaceAll("T", " ")); // 获取当日累计流量
//        Map<String, BigDecimal> monthFlowData = xjFlowDataDao.getFlowData(query.getStartMonthTime().toString().replaceAll("T", " ")
//                , query.getEndMonthTime().toString().replaceAll("T", " ")); // 获取当月累计流量
//        LocalDateTime updateTime = StringUtils.isBlank(maxTime) ? null : LocalDateTime.parse(maxTime.substring(0, 19), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//        xjList.forEach(xjData -> {
////            BigDecimal insFlow = insFlowData.get(xjFlowNameMap.get(xjData.getId()));
////            BigDecimal dayFlowSum = dayFlowData.get(xjFlowNameMap.get(xjData.getId()));
////            BigDecimal monthFlowSum = monthFlowData.get(xjFlowNameMap.get(xjData.getId()));
////            xjData
////                    .setFlow(Float.valueOf(insFlow.floatValue()))
////                    .setUpdateTime(updateTime)
////                    .setFlowSum(Float.valueOf(dayFlowSum.floatValue()))
////                    .setFlowSumMonth(Float.valueOf(monthFlowSum.floatValue()))
////            ;
//            if (ObjectUtils.isNotEmpty(insFlowData)) {
//                xjData.setFlow(Constant.bigDecimalToFloat(insFlowData.get(xjFlowNameMap.get(xjData.getId()))));
//            }
//            if (ObjectUtils.isNotEmpty(pmFlowData)) {
//                xjData.setFlowSumPm(Constant.bigDecimalToFloat(pmFlowData.get(xjFlowNameMap.get(xjData.getId()))));
//            }
//            if (ObjectUtils.isNotEmpty(dayFlowData)) {
//                xjData.setFlowSum(Constant.bigDecimalToFloat(dayFlowData.get(xjFlowNameMap.get(xjData.getId()))));
//            }
//            if (ObjectUtils.isNotEmpty(monthFlowData)) {
//                xjData.setFlowSumMonth(Constant.bigDecimalToFloat(monthFlowData.get(xjFlowNameMap.get(xjData.getId()))));
//            }
//            xjData.setUpdateTime(updateTime);
//        });
//
//        return xjList;
//    }

    public List<DataResultVO> getDataResult(List<DataResultVO> xjDataResult, DailyRecordListQuery query) {
        Map<String, Object> xjDataResultMap = xjFlowDataDao.getDataResult(
                query.getStartDateTime().toString().replaceAll("T", " ")
                , query.getEndDateTime().toString().replaceAll("T", " ")
                , query.getStartNightTime().toString().replaceAll("T", " ")
                , query.getEndNightTime().toString().replaceAll("T", " ")
                , String.valueOf(query.getHour())
        );
        Timestamp updateTimestamp = (Timestamp) xjDataResultMap.get("updateTime");
        LocalDateTime updateDateTime = updateTimestamp == null ? null : updateTimestamp.toLocalDateTime();
        xjDataResult.forEach(xjData -> {
            xjData.setUpdateTime(updateDateTime);
            Field[] fields = xjData.getClass().getDeclaredFields();

            for (int i = 5; i < fields.length; i++) {
                Field field = fields[i];
                String fieldName = field.getName();
                // 获取具体值
                field.setAccessible(true);
                // 其余情况根据类型赋值
                String fieldClassName = field.getType().getSimpleName();
                System.out.println(fieldName + " : " + fieldClassName);
                try {
                    field.set(xjData, xjDataResultMap.get(fieldName + xjData.getId()));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });

        return xjDataResult;
    }

    public void getTrendVo(TrendVO vo, DateInfoQuery query) {
        String start = LocalDateTime.of(query.getStartDate(), LocalTime.MIN).toString().replaceAll("T", " ");
        String end = LocalDateTime.of(query.getDate(), LocalTime.MIN).toString().replaceAll("T", " ");
        List<Map<String, Object>> mapList = xjFlowDataDao.getTrend(start, end);
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        String flowKey = xjFlowNameMap.get(vo.getId());
        mapList.forEach(map -> {
            HashMap<String, Object> data = new HashMap<>();
            data.put("time", map.get("time"));
            data.put("flowSum", map.get(flowKey));
            list.add(data);
        });
        vo.setList(list);
        ArrayList<Map<String, Object>> nightList = new ArrayList<>();
        List<Map<String, Object>> nightMapList = xjFlowDataDao.getNightTrend(start, end);
        nightMapList.forEach(map -> {
            HashMap<String, Object> data = new HashMap<>();
            data.put("time", map.get("time"));
            data.put("flowSum", map.get(flowKey));
            nightList.add(data);
        });
        vo.setNightList(nightList);
    }

    public void getDetailVo(DetailVO vo, DateInfoQuery query) {
        String date = LocalDateUtils.dateFormat(query.getDate(), LocalDateUtils.DATE_PATTERN);
        String end = LocalDateTime.of(query.getDate(), LocalTime.MIN).toString().replaceAll("T", " ");
        List<Map<String, Object>> mapList = xjFlowDataDao.getDetail(date);
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        String flowKey = xjFlowNameMap.get(vo.getId());
        mapList.forEach(map -> {
            HashMap<String, Object> data = new HashMap<>();
            data.put("time", map.get("time"));
            data.put("value", map.get(flowKey));
            list.add(data);
        });
        vo.setList(list);
    }


    /*    ------------------cpk----------------------*/

    public List<XjWaterSummary> getDailyWaterSupply(String startDate,String endDate) {
        return xjFlowDataDao.getDailyWaterSupply(startDate,endDate);
    }

    public List<Pair<String, Object>> getXjWaterDrawDaily(String startDate, String endDate) {
        return  xjFlowDataDao.getXjWaterDrawDaily(startDate,endDate);
    }

    public List<Pair<String, Object>> getMorningWaterOfXj(String startDate,String endDate) {
        return xjFlowDataDao.getMorningWaterOfXj(startDate,endDate);
    }


    public List<MonitorVO> getMonitorData(List<MonitorVO> xjList) {
        Map<String, Object> insData = xjFlowDataDao.getInsData();// 获取瞬时数据
        Timestamp updateTimestamp = (Timestamp) insData.get("time");
        LocalDateTime updateDateTime = updateTimestamp == null ? null:updateTimestamp.toLocalDateTime();
        xjList.forEach(xjData -> {
            if (ObjectUtils.isNotEmpty(insData)) {
                xjData.setFlowValue((BigDecimal) insData.get(xjFlowNameMap.get(xjData.getEquipmentId())));
                xjData.setPressValue((BigDecimal) insData.get(xjPressNameMap.get(xjData.getEquipmentId())));
            }
            xjData.setFlowTime(updateDateTime);
            xjData.setPressTime(updateDateTime);
        });

        return xjList;
    }

    public Object getCumulativeWaterOfXjSupply(String startDate) {
        return xjFlowDataDao.getCumulativeWaterOfXjSupply(startDate);
    }

    public Object getCumulativeWaterOfXjDraw(String startDate) {
        return xjFlowDataDao.getCumulativeWaterOfXjDraw(startDate);
    }

    public PageUtils queryPage(SqlServerDateQuery query) {
        // sqlserver2008 不支持mybatis自带的分页
        int total = xjFlowDataDao.getTotalCount(query.getEndDateTime(), query.getStartDateTime());
        List<XiJiangVO> list = xjFlowDataDao.page(
                query.getPage()*query.getLimit(), query.getLimit(), query.getEndDateTime(), query.getStartDateTime()
        );
        return new PageUtils(list, total, query.getLimit(), query.getPage());
    }
}